<template>
    <div class="discussion-container">
        <h2 class="discussion-title">题库讨论区</h2>
        <p class="discussion-subtitle">与同学们一起交流学习心得</p>

        <!-- 评论输入区 -->
        <div class="comment-input-area">
            <el-input v-model="commentContent" type="textarea" :rows="3" placeholder="请输入您的评论" resize="none"
                maxlength="500" show-word-limit />
            <el-button type="primary" class="submit-btn" @click="submitComment" :disabled="!commentContent.trim()">
                发布评论
            </el-button>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
            <div v-if="comments.length === 0" class="empty-comment">
                <p>暂无评论，快来发表你的见解吧~</p>
            </div>

            <div v-else class="comment-items">
                <div v-for="(comment, index) in comments" :key="comment.userId" class="comment-item">
                    <div class="comment-header">
                        <el-avatar :size="36" :src="comment.avatar" />
                        <div class="comment-user">
                            <span class="username">{{ comment.username }}</span>
                            <span class="comment-time">{{ formatTime(comment.time) }}</span>
                        </div>
                    </div>
                    <div class="comment-content">
                        <!-- 编辑状态显示输入框 -->
                        <el-input v-if="comment.editing" v-model="comment.editContent" type="textarea" :rows="4"
                            @blur="saveEdit(index)"
                            @keydown.enter="handleKeydownSave($event, index)"></el-input>
                        <!-- 非编辑状态显示内容 -->
                        <span v-else>{{ comment.content }}</span>
                        <!-- 操作按钮（只有当前用户才能看到自己的评论操作按钮） -->
                        <div class="comment-actions">
                            <div v-if="isCurrentUser(comment.userId)" >
                                <el-button type="text" :icon="Edit"  @click="editComment(index)">编辑</el-button>
                                <el-button type="text" :icon="Delete" @click="deleteComment(index)">删除</el-button>
                            </div>
                            <el-button v-else type="text" :icon="ChatDotRound" @click="replyToComment(index)">回复</el-button>
                        </div>
                    </div>

                    <!-- 回复输入框（点击回复时显示） -->
                    <div v-if="comment.showReplyInput" class="reply-input">
                        <el-input v-model="comment.replyContent" type="textarea" :rows="4"
                            placeholder="写下你的回复..."></el-input>
                        <div class="reply-actions">
                            <el-button size="small" @click="cancelReply(index)">取消</el-button>
                            <el-button type="primary" size="small" @click="submitReply(index)">回复</el-button>
                        </div>
                    </div>

                    <!-- 回复列表 -->
                    <div v-if="comment.replies && comment.replies.length > 0" class="reply-list">
                        <div v-for="(reply, replyIndex) in comment.replies" :key="reply.id" class="reply-item">
                            <div class="reply-header">
                                <el-avatar :size="24" :src="reply.avatar" />
                                <span class="reply-username">{{ reply.username }}</span>
                                <span class="reply-time">{{ formatTime(reply.time) }}</span>
                            </div>
                            <div class="reply-content">{{ reply.content }}</div>
                            <el-button v-if="isCurrentUser(reply.userId)" type="text" size="mini" style="display: flex;"
                                    @click="deleteReply(index, replyIndex)">删除</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script name="Discussion" lang="ts" >
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'; // 假设使用 Element Plus
import { userApi } from '@/api/Users';
import { UserData } from '@/types/UserData';
import { Edit, ChatDotRound, Delete, } from '@element-plus/icons-vue'

</script>
<script lang="ts" setup>
    // 评论内容
    const commentContent = ref('')
    // 评论列表
    const comments = ref([])
    // 用户信息
    const userData = ref<UserData>(null);
    // 回复
    interface Reply {
        id: number;
        userId: string | number;
        username: string;
        avatar: string;
        content: string;
        time: Date;
    }
    

    // 检查是否是当前用户的评论
    const isCurrentUser = (userId: string | number): boolean => {
        if (userData.value.userId === userId) {
            console.log("当前用户"+userData.value.userId)
            console.log("评论用户"+userId)
            return true;
        } else {
            return false;
        }
    };

    // 删除评论
    const deleteComment = (index: number) => {
        ElMessageBox.confirm('确定要删除这条评论吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            comments.value.splice(index, 1);
            ElMessage.success('删除成功!');
        }).catch(() => {
            ElMessage.info('已取消删除');
        });
    };
    // 编辑评论
    const editComment = (index: number) => {
        comments.value[index].editing = true;
        comments.value[index].editContent = comments.value[index].content;
    };

    // Enter键保存
    const handleKeydownSave = (event: KeyboardEvent, index: number) => {
        // 如果按下的是纯 Enter（没有 Shift 或 Ctrl），则保存
        if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey) {
            event.preventDefault(); // 阻止默认换行行为
            saveEdit(index); // 调用保存方法
        }
        // 如果是 Shift + Enter 或 Ctrl + Enter，允许换行（不处理）
    };

    // 保存编辑
    const saveEdit = (index: number) => {
        if (!comments.value[index].editContent?.trim()) {
            ElMessage.warning('评论内容不能为空');
            return;
        }

        comments.value[index].content = comments.value[index].editContent || '';
        comments.value[index].editing = false;
        // 这里可以添加保存到服务器的逻辑
    };

    // 回复评论
    const replyToComment = (index: number) => {
        comments.value.forEach((comment, i) => {
            comment.showReplyInput = i === index;
        });
    };

    // 提交回复
    const submitReply = (index: number) => {
        if (!comments.value[index].replyContent?.trim()) {
            ElMessage.warning('回复内容不能为空');
            return;
        }

        const newReply: Reply = {
            id: Date.now(),
            userId: userData.value.userId,
            username: userData.value.userName,
            avatar: userData.value.avatarPath,
            content: comments.value[index].replyContent || '',
            time: new Date()
        };

        if (!comments.value[index].replies) {
            comments.value[index].replies = [];
        }

        comments.value[index].replies.push(newReply);
        comments.value[index].replyContent = '';
        comments.value[index].showReplyInput = false;
    };

    // 取消回复
    const cancelReply = (index: number) => {
        comments.value[index].replyContent = '';
        comments.value[index].showReplyInput = false;
    };

    // 删除回复
    const deleteReply = (commentIndex: number, replyIndex: number) => {
        ElMessageBox.confirm('确定要删除这条回复吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            comments.value[commentIndex].replies?.splice(replyIndex, 1);
            ElMessage.success('删除成功!');
        }).catch(() => {
            ElMessage.info('已取消删除');
        });
    };


    // 模拟从API获取评论
    const fetchComments = () => {
        // 实际项目中这里应该是API调用
        comments.value = [
            {   
                userId: 11,
                username: '用户11',
                avatar: 'https://picsum.photos/50/50',
                content: '这是一条评论',
                time: new Date(),
            }
        ]
    }

    // 提交评论
    const submitComment = () => {
        if (!commentContent.value.trim()) return

        // 模拟API调用
        const newComment = {
            // id: comments.value.length + 1,
            userId: userData.value.userId,
            username: userData.value.userName,
            avatar: userData.value.avatarPath,
            content: commentContent.value.trim(),
            time: new Date()
        }

        comments.value.unshift(newComment)
        commentContent.value = ''
        ElMessage.success('评论发表成功')
    }

    // 简单的时间格式化
    const formatTime = (date) => {
        if (!(date instanceof Date)) {
            date = new Date(date)
        }
        return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
    }

    const padZero = (num) => {
        return num < 10 ? `0${num}` : num
    }

    
    // 初始化
    onMounted(async () => {
        // 初始化获取评论
        fetchComments()

        try {
            const res = await userApi.getLoginUserData();
            if (res) {
                userData.value = res;
                // console.log(userData.value);
            } else {
                ElMessage.error('获取用户信息失败');
            }
        } catch (error) {
            ElMessage.error('获取用户信息时出错');
            console.error(error);
        }
    });

</script>

<style scoped>
.discussion-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    height: 100%;
    overflow-y: auto;
}

.discussion-title {
    margin: 0 0 8px 0;
    font-size: 20px;
    color: #333;
    text-align: center;
}

.discussion-subtitle {
    margin: 0 0 24px 0;
    font-size: 14px;
    color: #666;
    text-align: center;
}

.reply-actions{
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
}

.reply-item{
    padding: 15px;
    margin-left: 20px;
}

.comment-input-area {
    margin-bottom: 24px;
}

.comment-input-area :deep(.el-textarea__inner) {
    border-radius: 6px;
    padding: 12px;
    margin-bottom: 12px;
}

.submit-btn {
    width: 120px;
    float: right;
}

.comment-list {
    clear: both;
}

.empty-comment {
    padding: 40px 0;
    text-align: center;
    color: #999;
    font-size: 14px;
    border-top: 1px solid #eee;
}

.comment-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
}

.comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}

.comment-user {
    margin-left: 12px;
}

.username {
    font-weight: 500;
    margin-right: 10px;
    color: #333;
}

.comment-time {
    font-size: 12px;
    color: #999;
}

.comment-content {
    margin-left: 48px;
    color: #333;
    line-height: 1.6;
    white-space: pre-wrap;
    max-width: 100%; /* 确保有最大宽度限制 */
    word-break: break-word; /* 确保长单词或URL能换行 */
}

.comment-actions{
    display: flex;
    justify-content: flex-end;
}
</style>